package schemup;

import java.sql.ResultSet;
import java.sql.SQLException;

import obj.Table;
import obj.Version;
import obj.tblVersion;

import setting.schemaTable;
import data.CurrentVersion;
import data.Db;
import data.ListTable;

public class SchemupRunner {

	public static void startSchemup() {
		loadCurrentVersion();
		doSchemup();

	}

	private static void doSchemup() {
		Table table = null;

		while ((table = ListTable.getTable()) != null) {
			processTable(table);
		}

	}

	private static void processTable(Table table) {
		int currentVersion = CurrentVersion.getCurrentVersion(table.tableName);
		Version version = null;
		while ((version = table.getNextVersion(currentVersion)) != null) {

			if (processVersion(version, table.tableName, currentVersion)) {
				System.out.println(table.tableName+" : "+currentVersion+" => "+ version.version);
				currentVersion = version.version;
			} else {
				System.out.println("Error on Table :" + table.tableName);
				System.exit(-1);
			}

		}

	}

	private static boolean processVersion(Version version, String tablename,
			int currentVersion) {
		Db.db.batchQuery(version.sql);
		if (currentVersion == 0) {
			Db.db.runQuery("INSERT INTO " + schemaTable.tablename
					+ " SET tablename='" + tablename + "',sversion="
					+ version.version);
		} else {
			Db.db.runQuery("UPDATE " + schemaTable.tablename + " SET sversion="
					+ version.version + " WHERE tablename='" + tablename + "'");
		}

		return true;
	}

	private static void loadCurrentVersion() {

		boolean isExist = Db.db.tableExist(schemaTable.tablename);
		if (!isExist) {
			createVersionTable();
		}

		
		ResultSet result = Db.db.select("SELECT * FROM "
				+ schemaTable.tablename);
		try {
			while (result.next()) {
				String tablename = result.getString("tablename");
				int version = result.getInt("sversion");

				tblVersion Version = new tblVersion(tablename, version);
				CurrentVersion.list.add(Version);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private static void createVersionTable() {
		String query = "CREATE TABLE "
				+ schemaTable.tablename
				+ " ( tablename varchar(50) UNIQUE NOT NULL, sversion int NOT NULL DEFAULT 0 );";
		
		Db.db.runQuery(query);
	}

}
